package top.lyjwn.ajui.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.util.Log;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.lyjwn.ajui.util.TokenUtil;

public class HttpUtil {

    /**
     * 连接清理线程池
     */
    private static ScheduledExecutorService leisureConnectCleanService = Executors.newSingleThreadScheduledExecutor();

    /**
     * 连接清理任务
     */
    private static LeisureConnectCleanTask leisureConnectCleanTask = new LeisureConnectCleanTask();


    /**
     * 请求类型
     */
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    /**
     * http连接机
     */
    public static OkHttpClient client = null;

    private static OkHttpClient getClient() {
        if (client == null) {
            synchronized (HttpUtil.class) {
                client = new OkHttpClient();
                client.newBuilder()
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.SECONDS)
                        .writeTimeout(15, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(false);
                leisureConnectCleanService.scheduleAtFixedRate(leisureConnectCleanTask, 10, 10, TimeUnit.SECONDS);
            }
        }
        return client;
    }

    /**
     * 获得通用的请求头部
     *
     * @param url
     * @return
     */
    public static Request.Builder getBuilder(String url) {
        return new Request.Builder().url(url)
                .addHeader("Content-Type", "charset=utf-8")
                .addHeader("X-Requested-With", "xmlhttprequest")
                .addHeader("token", TokenUtil.getToken()==null?"":TokenUtil.getToken().getToken())
                .removeHeader("User-Agent");
    }




    /**
     * get方法
     *
     * @param url
     * @param callback
     * @throws IOException
     */
    public static void get(String url, final Callback callback) {
        final Request request = getBuilder(url).get().build();
        getClient().newCall(request).enqueue(callback);

    }


    /**
     * post请求方式
     *
     * @param url                   请求地址
     * @param requestBody           请求参数
     * @param callback 回调监听器
     */
    public static void post(String url, RequestBody requestBody, final Callback callback) {
        final Request request = getBuilder(url).post(requestBody)
                .build();
        getClient().newCall(request).enqueue(callback);
    }

    /**
     * post请求方式
     *
     * @param requestBody
     * @param callback
     */
    public static void post(PostRequestBody requestBody, final Callback callback) {
        post(requestBody.getUrl(), requestBody.getRequestBody(), callback);
    }

    /**
     * post上传图片
     *
     * @param url                   请求地址
     * @param requestBody           请求参数
     * @param callback 回调结果
     */
    public static void post(String url, MultipartBody.Builder requestBody, Callback callback) {
        final Request request = getBuilder(url)
                .post(requestBody.build())
                .build();
        getClient().newCall(request).enqueue(callback);
    }



    /**
     * 网络图片同步获取方法
     * 创建一个get请求
     * 设置一个路径
     * <p>
     * 调用同步请求方法
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static Response getInSync(String url) {
        Request build = getBuilder(url).build();
        Call call = getClient().newCall(build);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            Log.e("同步http请求失败", "url=>" + url);
            e.printStackTrace();
        }
        return response;
    }




    /**
     * 空闲连接清理
     *
     * @author luoyujie
     */
    private static class LeisureConnectCleanTask implements Runnable {

        @Override
        public void run() {
            if (client != null) {
                try {
                    client.connectionPool().evictAll();
                } catch (Exception e) {
                    Log.e("http client clean", e.getMessage() + "");
                }
            }
        }
    }
}
